package com.yxr.filter;

import com.alibaba.fastjson.JSON;
import com.yxr.domain.ResponseResult;
import com.yxr.domain.entity.LoginUser;
import com.yxr.enums.AppHttpCodeEnum;
import com.yxr.utils.JwtUtil;
import com.yxr.utils.RedisCache;
import com.yxr.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;



    //定义过滤器链，判断访问的用户是否合法登录，权限设置
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            //说明接口不需要登录放行
            filterChain.doFilter(request,response);
            return;
        }

        //解析获取userid
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);

        } catch (Exception e) {
            e.printStackTrace();
            //token 超时  非法
            //响应告诉前端需要重新登录
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
            return;

        }
        String userid = claims.getSubject();
        //从redis获取用户信息
        LoginUser cacheObject = redisCache.getCacheObject("login:" + userid);
        //如果获取不到

        if(Objects.isNull(cacheObject)){
            //说明过期了
            //响应告诉前端需要重新登录
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
            return;

        }
        //存入securityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(cacheObject,null,null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}
